// CSimpleTray - Simple tray icon implementation

#include "stdafx.h"
#include "SimpleTray.h"

#define ID_SYS_TRAY	1

// constructor
CSimpleTray::CSimpleTray(UINT uiTrayNotificationMessage)
{
	// initialize 
	m_hIcon = NULL;
	m_strTooltip = "";
	m_bEnabled = FALSE;
	m_uiTrayNotificationMessage = uiTrayNotificationMessage;
}

// destructor
CSimpleTray::~CSimpleTray()
{
	Hide(); // a good thing to do :-)
}

// shows the tray icon
bool CSimpleTray::Show()
{
	// check to see if we have a valid icon
	if ( m_hIcon == NULL )
		return false;

	// make sure we are not already visible
	if ( m_bEnabled == TRUE )
		return true;

	// initialize the TRAYNOTIFYDATA struct
	m_nid.cbSize	= sizeof(m_nid);

	m_nid.hWnd		= AfxGetMainWnd()->m_hWnd;	// the 'owner' window
	// this is the window that
	// receives notifications
	m_nid.uID		= ID_SYS_TRAY;	// ID of our icon, as you can have
	// more than one icon in a single app

	m_nid.uCallbackMessage = m_uiTrayNotificationMessage;	// our callback message
	_tcscpy_s(m_nid.szTip, m_strTooltip);	// set the tooltip
	m_nid.hIcon = m_hIcon;	// icon to show

	m_nid.uFlags =	NIF_MESSAGE |	// flags are set to indicate what
		NIF_ICON |		// needs to be updated, in this case
		NIF_TIP;		// callback message, icon, and tooltip

	bool bSuccess = false;
	for (int i=0;i<10;i++)
	{
		if (Shell_NotifyIcon( NIM_ADD, &m_nid ))	// finally add the icon
		{
			m_bEnabled = TRUE;	// set our indicator so that we
			// know the current status
			bSuccess = true;
			break;
		}
		Sleep(300);
	}
	return bSuccess;
}


// hides the tray icon
void CSimpleTray::Hide()
{
	// make sure we are enabled
	if ( m_bEnabled == TRUE )
	{
		// we are, so remove
		m_nid.uFlags = 0;
		for (int i=0;i<10;i++)
		{
			if (Shell_NotifyIcon( NIM_DELETE, &m_nid ))
				break;
			Sleep(300);
		}

		m_bEnabled = FALSE;
	}
}

// updates tray with a new icon
void CSimpleTray::SetIcon(HICON hIcon)
{
	// first make sure we got a valid icon
	if ( hIcon == NULL )
		return;

	// set it as our private
	m_hIcon = hIcon;

	// now check if we are already enabled
	if ( m_bEnabled == TRUE )
	{	// we are, so update
		m_nid.hIcon = m_hIcon;
		m_nid.uFlags = NIF_ICON;	// only icon
		for (int i=0;i<10;i++)
		{
			if (Shell_NotifyIcon( NIM_MODIFY, &m_nid ))
				break;
			Sleep(300);
		}
	}
}

// updates tray with a new tooltip
void CSimpleTray::SetTooltip(LPCTSTR lpTooltip)
{
	// tooltip can be empty, we don't care
	m_strTooltip = lpTooltip;

	// if we are enabled
	if ( m_bEnabled == TRUE )
	{	// do an update
		_tcscpy_s(m_nid.szTip, m_strTooltip);
		m_nid.uFlags = NIF_TIP;	// tooltip only
		for (int i=0;i<10;i++)
		{
			if (Shell_NotifyIcon( NIM_MODIFY, &m_nid ))
				break;
			Sleep(300);
		}
	}
}

BOOL CSimpleTray::IsEnabled()
{
	return m_bEnabled;
}
